public class Solution1026 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int ans=0;

    public int maxAncestorDiff(TreeNode root) {
        dfs(root,root.val,root.val);
        return ans;
    }

    private void dfs(TreeNode root, int min, int max) {
        if (root==null){
            return;
        }
        ans=Math.max(ans,Math.abs(root.val-min));
        ans=Math.max(ans,Math.abs(root.val-max));
        dfs(root.left,Math.min(min,root.val),Math.max(max,root.val));
        dfs(root.right,Math.min(min,root.val),Math.max(max,root.val));
    }

    public static void main(String[] args) {
        System.out.println(new Solution1026().maxAncestorDiff(new TreeNode(8,new TreeNode(3,new TreeNode(1),new TreeNode(6,new TreeNode(4),new TreeNode(7))),new TreeNode(10,null,new TreeNode(14,new TreeNode(13),null)))));
    }
}
